package xin.codedream.codelog.service.impl;

import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xin.codedream.codelog.dao.TagDao;
import xin.codedream.codelog.model.entity.Tag;
import xin.codedream.codelog.service.TagsService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 标签功能业务层实现
 *
 * @author NGLSL
 * @date 2018/8/13
 */
@Service
public class TagsServiceImpl implements TagsService {
    @Resource
    private TagDao tagDao;

    @Override
    public List<Tag> findAllTags(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize, true);
        return tagDao.listAllTags();
    }

    @Override
    public Tag findTagByName(String tagName) {
        return tagDao.selectTagByName(tagName);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Tag saveTag(Tag tag) {
        tagDao.insertTag(tag);
        return tag;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Tag> strConversionToTags(String tags) {
        List<Tag> tagList = new ArrayList<>();
        if (StringUtils.isEmpty(tags)) {
            return tagList;
        }
        String[] strTags = tags.split(",");
        for (String strTag : strTags) {
            Tag tag = findTagByName(strTag);
            if (Objects.isNull(tag)) {
                tag = new Tag();
                tag.setTagName(strTag);
                tag.setTagPath(strTag);
                tagList.add(saveTag(tag));
            } else {
                tagList.add(tag);
            }
        }
        return tagList;
    }

    @Override
    public boolean removeTagByTagId(Long tagId) {
        return tagDao.deleteTagByTagId(tagId) > 0;
    }

    @Override
    public boolean removeTag(Long tagId) {
        boolean tagRemoveResult = this.removeTagByTagId(tagId);
        boolean articleTagRemoveResult = true;
        if (tagDao.countArticleTagByTagId(tagId) > 0) {
            articleTagRemoveResult = tagDao.deleteArticleTagByTagId(tagId) > 0;
        }
        if (tagRemoveResult && articleTagRemoveResult) {
            return true;
        } else {
            throw new RuntimeException("标签删除失败，标签ID：" + tagId);
        }
    }

    @Override
    public Tag findTagInfoByTagId(Long tagId) {
        return tagDao.selectTagInfoByTagId(tagId);
    }
}
